<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/10/9 10:48
 * Desc:
 */
class Service_Api_Spot extends Contract_Api_Product
{

    use Trait_Api_Spot;

    /**
     * 景点类型ID
     */
    const TYPE_ID = 5;


    public function search(array $params = array()): array
    {
        if (!empty($params['tag']) && $params['tag'] == 'near') {
            //周边景点距离
            $distance           = Model_Sysconfig::get_sys_conf('value', 'cfg_plugin_spot_map_distance');
            $distance           = $distance ?: 4000;
            $params['lat']      = floatval($params['lat']);
            $params['lng']      = floatval($params['lng']);
            $params['distance'] = $distance;
        }
        $data = Model_Api_V2_Spot::search($params);
        $uni_img = Model_Uniapp_Images::get_img_list(self::TYPE_ID);
        if (!empty($data['list'])) {
            $marketing_strategy = Model_Api_V2_Marketing_Strategy::get_instance(self::TYPE_ID, array('mid'=> $params['mid']));
            foreach ($data['list'] as &$v) {
                if(isset($uni_img[$v['id']])){
                    $v['litpic'] = $uni_img[$v['id']];
                }
                $v['price']       = Model_Spot::get_minprice($v['id'], $v);
                $v['price']       = $v['price']['price'];
                $v['attrlist']    = Model_Spot::spot_attr($v['attrid']);
                $v['comment_num'] = Model_Comment::get_comment_num($v['id'], self::TYPE_ID); //评论次数
                $v['litpic']      = $this->img_url($v['litpic'], 750, 750);
                $v['iconlist']    = $this->icons($v['iconlist']);
                $v['score']       = St_Functions::get_satisfy(self::TYPE_ID, $v['id'], $v['satisfyscore']);
				$v['marketing_strategy'] = $marketing_strategy->get_support_application($v['id']);
                $v['satisfy']     = str_replace('%', '', $v['score']);
                $v['few_stars']   = St_Functions::few_stars($v['score']);
                $v['sellpoint']   = empty($v['sellpoint']) ? '' : $v['sellpoint'];
            }
        }

        $result = array(
            'total' => $data['total'],
            'list' => $data['list'],
        );

        if (isset($distance)) {
            $result['distance'] = $distance;
        }
        return $result;
    }

    public function info(array $params = array()): array
    {
        $data = Model_Api_V2_Spot::detail($params);

        if (empty($data)) {
            return $data;
        }

        // 处理视频
        if ($data['product_video']) {
            $product_video         = explode('|', $data['product_video']);
            $data['product_video'] = isset($product_video[0]) ? $this->reorganized_resource_url($product_video[0]) : '';
        } else {
            $data['product_video'] = '';
        }

        $uni_img = Model_Uniapp_Images::get_img_list(self::TYPE_ID,2);
        if(isset($uni_img['litpic'][$data['id']])){
            $data['piclist'] = $uni_img['piclist'][$data['id']];
            $data['litpic'] = $uni_img['litpic'][$data['id']];
        }

        // 图片列表
        $data['pic_list'] = $this->pic_list_url($data['piclist']);
        //产品封面图片
        $data['litpic'] = $this->img_url($data['litpic'],750,750);

        Model_Api_V2_Spot::calc_days($data);

        $type_map = DB::select('id', 'kindname')
            ->from('spot_ticket_type')
            ->where('spotid', '=', $data['id'])
            ->execute()
            ->as_array('id', 'kindname');
        $refund_class = Service_Refund_Rule_Factory::get_instance(self::TYPE_ID);
        $data['suit_list'] = array_values(array_reduce($data['suit_list'], function ($rs, $item) use ($type_map, $refund_class) {
            if (!isset($rs[$item['tickettypeid']])) {
                $rs[$item['tickettypeid']] = array('typename' => $type_map[$item['tickettypeid']], 'child' => array());
            }

            unset($item['addtime']);
            unset($item['modtime']);
            unset($item['displayorder']);
            unset($item['eticketType']);
            unset($item['eticketsmssign']);
            unset($item['eticketsmstemplet']);
            unset($item['lastoffer']);
            unset($item['create_type']);
            unset($item['interface_code']);
            unset($item['supplier_channel_id']);
            unset($item['settlement_type']);
            unset($item['supplierlist']);

            $item['tickettype_name'] = $type_map[$item['tickettypeid']];
            $item['refund_restriction_name']  = $refund_class->get_refund_restriction_name($item['refund_restriction']);

            array_push($rs[$item['tickettypeid']]['child'], $item);

            return $rs;
        }, array()));

        foreach ($data['suit_list'] as &$v) {
            $v['typename'] = $v['typename']?: '';
        }

        unset($data['webid']);
        unset($data['aid']);
        unset($data['price_date']);
        unset($data['addtime']);
        unset($data['modtime']);
        unset($data['wap_templet']);
        unset($data['supplier_channel_id']);
        unset($data['templet']);

        return $data;
    }

    public function query_condition(): array
    {
        $data = array(
            'sort' => array(
                array('id' => 0, 'name' => '综合排序'),
                array('id' => 1, 'name' => '价格从低到高'),
                array('id' => 2, 'name' => '价格从高到低'),
                array('id' => 3, 'name' => '销量优先'),
                array('id' => 4, 'name' => '人气推荐')
            ),
            'price' => array('name' => '价格', 'child' => array()),
        );

        // 价格
        $data['price']['child'] = Model_Api_V2_Spot::get_prices();

        // 属性
        $data['attribute'] = Model_Api_V2_Spot::get_attributes();

        return $data;
    }

    public function create_order(array $params = array()): array
    {
        $order_service = new Service_Api_Spot_Order($params);
        $order_service->order_check();
        $order_service->set_order_data();

        /*附加信息*/
        $extend_params = array(
            'member_card_id' => Arr::get($params, 'member_card_id', ''),
            'card_tourist_id' => Arr::get($params, 'card_tourist_id', ''),
            'use_member_discount' => false,
        );

        //写入主订单
        $order_res = Model_Api_V2_Order::add_order($order_service->order_info, 'Model_Spot', $extend_params);
        if (!$order_res['status']) {
            throw new Exception($order_res['msg']);
        }

        // 写入子订单
        $extend_params['use_member_discount'] = $order_service->use_member_discount;
        foreach ($order_service->child_orders as $child) {
            $child_data        = $child['order'];
            $child_data['pid'] = $order_res['order_id'];
            $child_order       = Model_Api_V2_Order::add_order($child_data, 'Model_Spot', $extend_params);
            $child_order_id    = $child_order['order_id'];

            // 库存
            Model_Spot_Ticket_Price::sub_stock($child_data, $child['sku_id']);

            // 游客
            if (!empty($child['tourist'])) {
                Model_Api_V2_Spot::add_order_tourists($child['tourist'], $child_order_id);
            }

            // 规格记录
            if (!empty($child['sku_id'])) {
                Model_Api_V2_Spot::add_order_sku($child['sku_id'], $child_order_id, $child_data['productautoid'], $child_data['suitid']);
            }
        }

        // 订单信息
        $order_info = Model_Member_Order::order_info($order_res['ordersn']);

        //优惠券使用
        $order_service->check_coupon($order_info);

        // 订单创建完成数据处理
        $order_service->create_after($order_info, $extend_params);

        // 事件
        Hook::trigger('order_created', $order_info);

        // 返回订单信息
        $order_info['orderid'] = $order_info['id'];
        $filter_keys           = array('id', 'orderid', 'ordersn', 'pageType', 'typeid', 'status');
        return $this->filter_data($filter_keys, $order_info);
    }
}